<script setup >
import {ref, computed, useTemplateRef,watch } from "vue";
import {c} from "naive-ui";
const emit = defineEmits(['onReady'])
const code = defineModel()

const state = ref({
  pos:0,
  SelectLine:0,
  lines:[]
})



watch(() => code.value, (value, oldValue) => {
  let oldLines = state.value.lines;

  // 将 oldLines 转换为 Map 以便快速查找
  const oldLinesMap = new Map(oldLines.map(line => [line.text, line.state]));

  // 处理新行
  state.value.lines = value.toString().split("\n").map(text => ({
    text,
    state: oldLinesMap.get(text) ?? false, // 使用 Map 查找状态，若没有找到则默认为 false
  }));
});



onMounted(()=>{
  emit('onReady',(view,state)=>{

  })
  state.value.lines = code.toString().split("\n").map((text)=>{
    return {
      text:text,
      state:false
    }})
})

const refCode = useTemplateRef('refCode')

window.codeAPI.onGetCode((value) => {
  let space = ""
  for (let i = 0; i < state.value.lines[state.value.SelectLine].text.toString().match(/ /g).length; i++) {
    space += " "
  }
  if (value.info.toString().startsWith("（") && value.info.toString().endsWith("）")){

  }else {
    space += "    "
  }

  let data = ""
  let s = value.info.toString().split("\n")
  for (let i = 0; i < s.length; i++) {
    if (i === s.length-1) {
      data += space+s[i]
      break
    }
    data += space+s[i]+"\n"
  }
  state.value.lines[state.value.SelectLine].state = true
  addAbs(data)
})

function addAbs(value) {
  let line = state.value.SelectLine
  // let last = state.value.lines[line].text.match(/ /g).length
  // let next = 0
  // if (line+1 < state.value.lines.length){
  //   next = state.value.lines[line+1].text.match(/ /g).length
  //   if (last > next){
  //     return
  //   }
  // }

  state.value.lines.splice(line+1,0,{text:value,state: false})
  console.log(state.value.lines)
  let text = ''
  state.value.lines.map((item)=>text += item.text + '\n')
  text = text.trim()
  code.value = text
}

function handlePlus (index) {
  state.value.SelectLine = index
  if (state.value.lines[index].state){
    return
  }
  const data = {
    source: "user",
    action: "getCode",
    target: state.value.lines[index].text.trim(),
    state: "",
    info: ""
  }
  window.codeAPI.sendCode(data)
}

function handleClick (event) {
  state.value.pos = refCode.value.selectionStart
  let len = 0
  for (let i = 0; i < state.value.lines.length; i++) {
    len += state.value.lines[i].text.length
    if (state.value.pos <= len){
      // console.log("pos :",pos)
      // console.log("len :",len)
      // console.log(codelist.value[i])
      state.value.SelectLine = i
      return
    }
    len++
  }

}

function getState(index){
  if (index+1 >= codeList.value.length ) return true
  let line = codeList.value[index]
  let nextLine = codeList.value[index+1]

  if (line.toString().trim() !== nextLine.toString().trim()) return true
  return false;
}



</script>

<template>
  <div id="textarea-container">

    <div id="line-numbers">
      <template v-for="({state},index) in state.lines" >
        <div class="left">
          <div class="line-numbers"> {{ index +1 }}</div>
          <div class="state" @click="()=>handlePlus(index)">{{ state ? "-" : "*" }}</div>
        </div>
      </template>
    </div>
    <textarea ref="refCode" @click="handleClick" v-model="code" />
  </div>
</template>

<style scoped>
#textarea-container {
  width: 100%;
  height:100%;
  display: flex;
}
#line-numbers {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 5px;
  width: 40px;
  font-size: 13px;
  color: #808080;
  line-height: 26px;
}

.left{
  width: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  align-content: stretch;
}
.number{

}

textarea{
  width: 100%;
  height: 100%;
  outline: none;
  border: 1px solid #ccc;
  border-radius: 0 4px 4px 0;
  padding: 8px;
  resize: none; /* 禁止调整大小 */
  font-size: 16px;
  line-height: 26px;
  overflow: hidden;  /* 禁止滚动条 */
}
</style>